﻿
namespace Patterns4Net.ArchitectureExplorer.Diagram.Services.Relations
{
    using System.Linq;
    using Mono.Cecil;
    using Attributes.Relations;
    using Core.CecilExtensions;
    using ArchitectureExplorer.Diagram.Relations;

    [DiagramUpdaterExport(Order = 10)]
    public class InheritanceProvider : RelationsProvider
    {
        protected override void Visit(TypeInfo typeInfo, TypeDefinition typeDefinition)
        {
            var resolvedIfaces = typeDefinition.Interfaces.Select(i => i.Resolve()).Where(i => i != null);

            foreach (var iface in typeDefinition.Interfaces)
            {
                if (resolvedIfaces.Any(i => i.IsEqual(iface) == false && i.Implements(iface)))
                {
                    // filter transitive inheritance when one of the ifaces implements some other.
                    continue;
                }

                this.AddRelationIfExists(typeInfo, iface);
            }

            if (typeDefinition.BaseType != null)
            {
                this.AddRelationIfExists(typeInfo, typeDefinition.BaseType);
            }
        }

        protected override Relation CreateRelation(DiagramElement source, DiagramElement target, Cardinality cardinality)
        {
            return new Inheritance(source, target);
        }

        protected override bool IsMadeObsoleteBy(Relation relation)
        {
            return relation.GetType() == typeof(Inheritance);
        }
    }
}
